<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>空气质量监测系统 - 登录测试面板</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            color: #333;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eaeaea;
        }
        h1 {
            color: #409EFF;
            margin-bottom: 5px;
        }
        h3 {
            font-weight: normal;
            color: #606266;
            margin: 5px 0;
        }
        .test-group {
            margin-bottom: 25px;
            padding: 15px;
            border: 1px solid #E4E7ED;
            border-radius: 4px;
        }
        .btn {
            display: inline-block;
            line-height: 1;
            white-space: nowrap;
            cursor: pointer;
            background: #FFF;
            border: 1px solid #DCDFE6;
            color: #606266;
            -webkit-appearance: none;
            text-align: center;
            box-sizing: border-box;
            outline: none;
            margin: 0;
            transition: .1s;
            font-weight: 500;
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
            padding: 12px 20px;
            font-size: 14px;
            border-radius: 4px;
        }
        .btn-primary {
            color: #FFF;
            background-color: #409EFF;
            border-color: #409EFF;
        }
        .btn-success {
            color: #FFF;
            background-color: #67C23A;
            border-color: #67C23A;
        }
        .btn-warning {
            color: #FFF;
            background-color: #E6A23C;
            border-color: #E6A23C;
        }
        .btn-danger {
            color: #FFF;
            background-color: #F56C6C;
            border-color: #F56C6C;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
        }
        input {
            width: 100%;
            padding: 10px;
            border: 1px solid #DCDFE6;
            border-radius: 4px;
            box-sizing: border-box;
            margin-bottom: 10px;
        }
        .log-container {
            background-color: #1e1e1e;
            color: #dcdcdc;
            padding: 15px;
            border-radius: 4px;
            overflow: auto;
            height: 300px;
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
            font-size: 14px;
            margin-top: 20px;
        }
        .success {
            color: #67C23A;
        }
        .error {
            color: #F56C6C;
        }
        .warning {
            color: #E6A23C;
        }
        .info {
            color: #909399;
        }
        .token-display {
            background-color: #f8f8f8;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            font-family: Consolas, Monaco, 'Andale Mono', monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>空气质量监测系统</h1>
            <h3>登录与API集成测试面板</h3>
        </div>
        
        <div class="test-group">
            <h2>1. 登录测试</h2>
            <div class="form-group">
                <label for="username">用户名:</label>
                <input type="text" id="username" value="admin" autocomplete="username">
            </div>
            <div class="form-group">
                <label for="password">密码:</label>
                <input type="password" id="password" value="123456" autocomplete="current-password">
            </div>
            <button class="btn btn-primary" id="login-btn">登录测试</button>
            <button class="btn btn-danger" id="clear-token-btn">清除Token</button>
            
            <div id="token-info" style="margin-top: 15px; display: none;">
                <h3>Token 信息</h3>
                <div class="token-display" id="token-display"></div>
                <p>过期时间: <span id="expires-time"></span></p>
            </div>
        </div>
        
        <div class="test-group">
            <h2>2. API状态测试</h2>
            <button class="btn btn-success" id="api-status-btn">检查API状态</button>
            <button class="btn btn-warning" id="api-test-btn">测试API连通性</button>
        </div>
        
        <div class="log-container" id="log-container">
            <!-- 日志将在此显示 -->
        </div>
    </div>
    
    <script>
        // 日志工具
        const logger = {
            log: function(message, data) {
                const logContainer = document.getElementById('log-container');
                const logEntry = document.createElement('div');
                logEntry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
                logContainer.appendChild(logEntry);
                logContainer.scrollTop = logContainer.scrollHeight;
                
                if (data) {
                    console.log(message, data);
                }
            },
            info: function(message, data) {
                this.log(`[信息] ${message}`, data);
            },
            success: function(message, data) {
                const logContainer = document.getElementById('log-container');
                const logEntry = document.createElement('div');
                logEntry.innerHTML = `[${new Date().toLocaleTimeString()}] <span class="success">[成功] ${message}</span>`;
                logContainer.appendChild(logEntry);
                logContainer.scrollTop = logContainer.scrollHeight;
                
                if (data) {
                    console.log(`[成功] ${message}`, data);
                }
            },
            error: function(message, data) {
                const logContainer = document.getElementById('log-container');
                const logEntry = document.createElement('div');
                logEntry.innerHTML = `[${new Date().toLocaleTimeString()}] <span class="error">[错误] ${message}</span>`;
                logContainer.appendChild(logEntry);
                logContainer.scrollTop = logContainer.scrollHeight;
                
                if (data) {
                    console.error(`[错误] ${message}`, data);
                }
            },
            warning: function(message, data) {
                const logContainer = document.getElementById('log-container');
                const logEntry = document.createElement('div');
                logEntry.innerHTML = `[${new Date().toLocaleTimeString()}] <span class="warning">[警告] ${message}</span>`;
                logContainer.appendChild(logEntry);
                logContainer.scrollTop = logContainer.scrollHeight;
                
                if (data) {
                    console.warn(`[警告] ${message}`, data);
                }
            }
        };
        
        // Base64解码函数（用于JWT Token）
        function base64UrlDecode(input) {
            input = input.replace(/-/g, '+').replace(/_/g, '/');
            const pad = input.length % 4;
            if (pad) {
                input += new Array(5 - pad).join('=');
            }
            return atob(input);
        }
        
        // 显示Token信息
        function displayTokenInfo(token) {
            if (!token) {
                document.getElementById('token-info').style.display = 'none';
                return;
            }
            
            try {
                document.getElementById('token-info').style.display = 'block';
                document.getElementById('token-display').textContent = token;
                
                // 处理带有Bearer前缀的token
                const tokenValue = token.startsWith('Bearer ') ? token.substring(7) : token;
                const tokenParts = tokenValue.split('.');
                
                if (tokenParts.length !== 3) {
                    logger.warning('Token格式不正确，无法解析');
                    return;
                }
                
                // 解析Token
                const payload = JSON.parse(base64UrlDecode(tokenParts[1]));
                console.log('Token Payload:', payload);
                
                // 显示过期时间
                if (payload.exp) {
                    const expiresAt = new Date(payload.exp * 1000);
                    document.getElementById('expires-time').textContent = expiresAt.toLocaleString();
                    
                    // 检查是否已过期
                    const now = new Date();
                    if (expiresAt < now) {
                        logger.warning('Token已过期');
                    } else {
                        const diff = Math.floor((expiresAt - now) / (1000 * 60 * 60));
                        logger.info(`Token有效期还剩约 ${diff} 小时`);
                    }
                }
            } catch (e) {
                logger.error('解析Token时出错', e);
            }
        }
        
        // 登录函数
        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                logger.error('用户名和密码不能为空');
                return;
            }
            
            logger.info(`尝试登录 - 用户名: ${username}, 密码: ${'*'.repeat(password.length)}`);
            
            try {
                // 发送登录请求
                const response = await fetch('https://zmyzmy.xin/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json'
                    },
                    body: JSON.stringify({
                        username,
                        password
                    })
                });
                
                const data = await response.json();
                logger.info(`登录响应状态码: ${response.status}`);
                
                if (response.ok && data.code === 200 && data.data?.token) {
                    // 保存token
                    const token = data.data.token;
                    localStorage.setItem('token', `Bearer ${token}`);
                    
                    // 保存用户信息
                    if (data.data.userInfo) {
                        localStorage.setItem('userInfo', JSON.stringify(data.data.userInfo));
                        logger.info(`用户信息: ${data.data.userInfo.username}, 角色: ${data.data.userInfo.role}`);
                    }
                    
                    logger.success('登录成功！');
                    displayTokenInfo(`Bearer ${token}`);
                    return true;
                } else {
                    logger.error('登录失败', data);
                    return false;
                }
            } catch (error) {
                logger.error('登录请求异常', error);
                return false;
            }
        }
        
        // 检查API状态
        async function checkApiStatus() {
            logger.info('检查API状态...');
            
            try {
                const token = localStorage.getItem('token');
                
                if (!token) {
                    logger.warning('未找到Token，请先登录');
                    return false;
                }
                
                const response = await fetch('https://zmyzmy.xin/api/auth/status', {
                    headers: {
                        'Accept': 'application/json',
                        'Authorization': token
                    }
                });
                
                if (response.ok) {
                    const data = await response.json();
                    logger.success('API状态检查成功', data);
                    return true;
                } else {
                    logger.error(`API状态检查失败: ${response.status} ${response.statusText}`);
                    return false;
                }
            } catch (error) {
                logger.error('API状态检查异常', error);
                return false;
            }
        }
        
        // 测试API连通性
        async function testApiConnection() {
            logger.info('测试API连通性...');
            
            try {
                const response = await fetch('https://zmyzmy.xin/api/auth/test');
                
                if (response.ok) {
                    const data = await response.json();
                    logger.success('API连接成功', data);
                    return true;
                } else {
                    logger.error(`API连接失败: ${response.status} ${response.statusText}`);
                    return false;
                }
            } catch (error) {
                logger.error('API连接异常', error);
                return false;
            }
        }
        
        // 清除Token
        function clearToken() {
            localStorage.removeItem('token');
            localStorage.removeItem('userInfo');
            localStorage.removeItem('tokenExpires');
            document.getElementById('token-info').style.display = 'none';
            logger.info('已清除Token和用户信息');
        }
        
        // 初始化事件
        document.addEventListener('DOMContentLoaded', function() {
            // 登录按钮
            document.getElementById('login-btn').addEventListener('click', login);
            
            // API状态检查按钮
            document.getElementById('api-status-btn').addEventListener('click', checkApiStatus);
            
            // API连通性测试按钮
            document.getElementById('api-test-btn').addEventListener('click', testApiConnection);
            
            // 清除Token按钮
            document.getElementById('clear-token-btn').addEventListener('click', clearToken);
            
            // 初始化检查是否已登录
            const token = localStorage.getItem('token');
            if (token) {
                logger.info('检测到已存在的Token');
                displayTokenInfo(token);
            }
            
            logger.info('测试面板已初始化');
        });
    </script>
</body>
</html>
